package com.devbobcorn.nekoration.blocks.entities;

import javax.annotation.Nullable;

import com.devbobcorn.nekoration.client.rendering.ChunkModel;

import net.minecraft.block.Block;
import net.minecraft.block.BlockState;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.network.play.server.SUpdateTileEntityPacket;
import net.minecraft.tileentity.ITickableTileEntity;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.Direction;
import net.minecraft.world.World;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;

public class PrismapTableBlockEntity extends TileEntity implements ITickableTileEntity {
    @Nullable // May be accessed before onLoad
	// @OnlyIn(Dist.CLIENT) Makes it so this field will be removed from the class on the PHYSICAL SERVER
	// This is because we only want the ChunkModel on the physical client - its rendering only.
	@OnlyIn(Dist.CLIENT)
	public ChunkModel chunkModel;

    public PrismapTableBlockEntity() {
        super(ModTileEntityType.PRISMAP_TABLE_TYPE.get());
    }

    @Override
    public void tick() {
        // ...
    }

	// @OnlyIn(Dist.CLIENT) Makes it so this method will be removed from the class on the PHYSICAL SERVER
	// This is because we only want the MiniModel on the physical client - its rendering only.
	@OnlyIn(Dist.CLIENT)
	@Override
    public void load(BlockState state, CompoundNBT tag){
        super.load(state, tag);
		World world = getLevel();
		if (world == null || !world.isClientSide)
			return; // Return if the world is null or if we are on the logical server
		createIfNull();
	}

	public void createIfNull(){
		if (chunkModel == null)
			chunkModel = ChunkModel.forTileEntity(this);
	}

	public void refresh(){
		if (chunkModel != null && !chunkModel.getError())
			chunkModel.compile();
	}

    public CompoundNBT save(CompoundNBT tag){
        return super.save(tag);
    }

    @Nullable
	public SUpdateTileEntityPacket getUpdatePacket() {
		return new SUpdateTileEntityPacket(this.worldPosition, 2202, this.getUpdateTag());
	}

	public CompoundNBT getUpdateTag() {
		return this.save(new CompoundNBT());
	}

    @OnlyIn(Dist.CLIENT)
    public boolean shouldRenderFace(Direction dir) {
        return Block.shouldRenderFace(this.getBlockState(), this.level, this.getBlockPos(), dir);
    }
}
